<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace app\api\controller\v2;

use app\common\cachemodel\Recode as RecodeCacheModel;
use app\common\model\User;
use Exception;
use \think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\response\Json;

/**
 * @title 档案相关接口
 * @desc
 * @url /api/v2/recode
 * @version 2.0.0
 * Class Recode
 * @package app\api\controller\v2
 */
class Recode extends Auth
{
    protected $restActionList = ['index', 'read', 'save', 'update', 'delete'];

    /**
     * 初始化档案行星信息
     */
    private function init()
    {
        $field = 'r.id,r.name,r.type,r.year,r.month,r.day,r.hour,r.minute,r.timezone,birth_country,birth_province,birth_city,live_country,live_province,live_city,comments,isself,long_deg,long_min,ew,lat_deg,lat_min,ns,avatar,is_summer,uid,aid,sun,moon,merc,venu,mars,jupi,satu,non,lili,juno,asc,mc';
        try
        {
            $data = model('recode')
                ->alias('r')
                ->join('app_recode_astro ra', 'r.id=ra.rid', 'LEFT')
                ->where('r.uid', $this->user['id'])
                ->where('ra.sun is null')
                ->column($field, 'r.id');
        }
        catch (Exception $e)
        {
            $data = [];
        }

        $temp = [];

        if (!empty($data))
        {
            $Astro = new \app\astro\controller\Index();
            foreach ($data as $d)
            {
                $longitude = ($d['long_deg'] + $d['long_min'] / 60) * $d['ew'];
                $latitude = ($d['lat_deg'] + $d['lat_min'] / 60) * $d['ns'];
                // 查询当前星盘日月水金火木土等星落座落宫存入数据库
                $astro_data = $Astro->getTheRecodeAstro($d['year'], $d['month'], $d['day'], $d['hour'], $d['minute'], $longitude, $latitude, $d['timezone']);
                $astro_data['rid'] = $d['id'];
                $astro_data['create_time'] = time();

                $temp[] = $astro_data;
            }

            Db::table('wechat_backup_07_18_14_43_00.app_recode_astro')->insertAll($temp);
        }
    }

    /**
     * @title 所有档案
     * @method GET
     * @desc 无需另外传参
     * @readme /doc/api/recode/index.md
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function index()
    {
//        $this->init();
        // 缓存开启速度太慢
//        $data = (new RecodeModel())->getRecodeLists(['uid' => $this->user['id']]);

        $data = model('recode')
            ->alias('r')
            ->join('app_recode_astro ra', 'r.aid=ra.id', 'LEFT')
            ->field('r.id,r.name,r.type,r.year,r.month,r.day,r.hour,r.minute,r.timezone,birth_country,birth_province,birth_city,live_country,live_province,live_city,comments,isself,long_deg,long_min,ew,lat_deg,lat_min,ns,avatar,is_summer,uid,aid,sun,moon,merc,venu,mars,jupi,satu,non,lili,juno,asc,mc')
            ->where(['uid' => $this->user['id'], 'status' => 1])
            ->select();

        return show(200, '成功', $data);
    }

    /**
     * @title 查看档案
     * @method GET
     * @url /get
     * @readme /doc/api/recode/read.md
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function read()
    {
        $id = input('get.id/d');
        $ret = [];
        $data = model('recode')->alias('r')
            ->join('app_recode_astro ra', 'r.id=ra.rid', 'INNER')
            ->field('r.id,r.name,r.type,r.year,r.month,r.day,r.hour,r.minute,r.timezone,birth_country,birth_province,
            birth_city,live_country,live_province,live_city,comments,isself,long_deg,long_min,ew,lat_deg,lat_min,ns,avatar,is_summer,uid,aid,
            sun,moon,merc,venu,mars,jupi,satu,non,lili,juno,asc,mc')
            ->where(['r.id' => $id, 'uid' => $this->user['id']])
            ->find();
        if ($data != null)
        {
            $ret = $data;
        }

        return show(200, '成功', $ret);
    }

    /**
     * @title 新建档案
     * @method POST
     * @readme /doc/api/recode/save.md
     * @return Json
     * @throws Exception
     */
    public function save()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = input('post.');
        // 进行参数校验
        $validate = validate('Recode');

        if (!$validate->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $param['uid'] = $this->user['id'];

        // 查询是否为自己
//        if(($comments == '自己' || $isself == 1) && $this->isself($uid))
//            return json(['code'=>10303,'msg'=>"Can't add more recode for your self."]);

        $time = time();
        $RecodeCacheModel = new RecodeCacheModel();
        $Astro = new \app\astro\controller\Index();
        $longitude = ($param['long_deg'] + $param['long_min'] / 60) * $param['ew'];
        $latitude = ($param['lat_deg'] + $param['lat_min'] / 60) * $param['ns'];
        // 查询当前星盘日月水金火木土等星落座落宫存入数据库
        $astro_data = $Astro->getTheRecodeAstro($param['year'], $param['month'], $param['day'], $param['hour'], $param['minute'], $longitude, $latitude, $param['timezone']);

        try
        {
//            $rid = model('recode')->insertGetId($param);// 返回自增id
            $rid = $RecodeCacheModel->SaveData($this->user['id'], $param);

            if ($param['comments'] == '自己' || $param['isself'] == 1)
            {
                //删除用户缓存
                (new User())->updateUserinfo(['id' => $this->user['id']], ['has_self_recode' => 1]);
//                model('user')->where(['id' => $this->user['id']])->update(['has_self_recode' => 1]);// 更新用户已有档案  1
            }
        }
        catch (Exception $e)
        {
            return show(config('code.error'), '保存失败', [], 500);
        }


        if (!$rid)
        {
            return json(['code' => 10301, 'msg' => '操作失败']);
        }

        $astro_data['rid'] = $rid;
        $astro_data['create_time'] = $time;

        Db::table('app_recode_info')->insertGetId(['rid' => $rid, 'create_time' => $time, 'last_time' => $time]);// 新增当前档案访问数据

        $aid = Db::table('app_recode_astro')->insertGetId($astro_data);// 新增当前档案行星数据

        $data['id'] = $rid;

//        Db::table('app_recode')->where(['id' => $rid])->update(['aid' => $aid]);// 更新aid字段

        $RecodeCacheModel->UpdateData($this->user['id'], $rid, ['aid' => $aid]);

        return show(200, '保存成功', array_merge($data, $astro_data));
    }

    /**
     * @title 编辑档案
     * @method PUT
     * @readme /doc/api/recode/update.md
     * @return Json
     */
    public function update()
    {
        return show(200, '更新成功', []);
    }

    /**
     * @title 删除档案
     * @method DELETE
     * @readme /doc/api/recode/delete.md
     * @return Json
     * @throws Exception
     */
    public function delete()
    {
        $id = (int)(input('id'));// 档案id
        if (!$id)
        {
            return json(['code' => 10307, 'msg' => 'Illegal operation.']);
        }
//        $Userinfo = new \app\user\controller\Userinfo();
//        $uid = $Userinfo->getUidByUcid();
        $uid = $this->user['id'];
        $RecodeCacheModel = new RecodeCacheModel();
        // 查询档案
        $data = Db::table('app_recode')->where(['id' => $id, 'uid' => $uid])->find();
        if (empty($data))
        {
            return json(['code' => 10308, 'msg' => 'Recode is not exited.']);
        }
        if ($data['isself'] == 1)
        {
            return json(['code' => 10309, 'msg' => 'Recode for your self can not be cancle.']);
        }
        // 查询是否为名人星案 无法删除
        $f_data = Db::table('app_recode_famous')->where(['rid' => $id, 'uid' => $uid, 'status' => 1])->select();
        if (!empty($f_data))
        {
            return json(['code' => 10310, 'msg' => 'Can not delete this.']);
        }
        // 查询该档案下的笔记 无法删除
        $n_data = Db::table('app_recode_note')->where(['rid' => $id, 'uid' => $uid])->select();
        if (!empty($n_data))
        {
            return json(['code' => 10311, 'msg' => 'Can not delete this.']);
        }
        // 删除文件
        if (is_file($data['avatar']))
        {
            if (!is_readable($data['avatar']))
            {
                return json(['code' => 10312, 'msg' => 'File can not be changed.']);
            }
            @unlink($data['avatar']);
        }
        Db::table('app_recode_cat')->where('rid', $id)->delete();

//        Db::table('app_recode')->where(['id' => $id, 'uid' => $uid])->update(['status' => 0]);

        $RecodeCacheModel->DelData($uid, $id, ['status' => 0]);
        return show(200, 'DELETE Success.', []);
    }

    /**
     * 参数规则
     * @ string name 字段名称
     * @ int type 类型
     * @require 是否必须
     * @default 默认值
     * @desc 说明
     * @range 范围
     * @return array
     */
    public static function getRules()
    {
        $rules = [
            'index' => [

            ],
            'read' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '档案id', 'range' => '',],
            ],
            'save' => [
                'name' => ['name' => 'name', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '档案名称', 'range' => '15字以内',],
                'type' => ['name' => 'type', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '档案性别/类别', 'range' => '1男 | 2 女 | 3 男同 | 4 女同 | 5 事件 | 6 卜卦',],
                'year' => ['name' => 'year', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生年', 'range' => '1900~2099',],
                'month' => ['name' => 'month', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生月', 'range' => '1~12',],
                'day' => ['name' => 'day', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生日', 'range' => '1~31',],
                'hour' => ['name' => 'hour', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生时', 'range' => '0~23',],
                'minute' => ['name' => 'minute', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生分', 'range' => '0~59',],
                'timezone' => ['name' => 'timezone', 'type' => 'int', 'require' => 'true', 'default' => '8（中国时区）', 'desc' => '时区', 'range' => '-12~12',],
                'birth_country' => ['name' => 'birth_country', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '出生省', 'range' => '',],
                'birth_province' => ['name' => 'birth_province', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '出生市', 'range' => '',],
                'birth_city' => ['name' => 'birth_city', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '出生区', 'range' => '',],
                'live_country' => ['name' => 'live_country', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '现居省', 'range' => '',],
                'live_province' => ['name' => 'live_province', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '现居市', 'range' => '',],
                'live_city' => ['name' => 'live_city', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '现居区', 'range' => '',],
                'comments' => ['name' => 'comments', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '标签', 'range' => '自己 | 恋人 | 朋友 | 亲友 | 工作 | 客户 | 案例 | 其他',],
                'isself' => ['name' => 'isself', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '是否自己', 'range' => '档案是否为自己 0 否 | 1 是（自己的档案无法删除，无法更改为其他标签）',],
                'long_deg' => ['name' => 'long_deg', 'type' => 'int', 'require' => 'true', 'default' => '0', 'desc' => '经度-度', 'range' => '0~180',],
                'long_min' => ['name' => 'long_min', 'type' => 'int', 'require' => 'true', 'default' => '0', 'desc' => '经度-分', 'range' => '0~59',],
                'ew' => ['name' => 'ew', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '东经|西经', 'range' => '1|-1',],
                'lat_deg' => ['name' => 'lat_deg', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '纬度-度', 'range' => '0~90',],
                'lat_min' => ['name' => 'lat_min', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '纬度-分', 'range' => '0~59',],
                'ns' => ['name' => 'ns', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '南纬北纬', 'range' => '1|-1',],
                'is_summer' => ['name' => 'is_summer', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '是否开启夏令时', 'range' => '0|1',],
                'avatar' => ['name' => 'avatar', 'type' => 'string', 'require' => 'false', 'default' => '无', 'desc' => '头像地址', 'range' => '',],
            ],
            'update' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '档案id', 'range' => '',],
                'name' => ['name' => 'name', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '档案名称', 'range' => '15字以内',],
                'type' => ['name' => 'type', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '档案性别/类别', 'range' => '1男 | 2 女 | 3 男同 | 4 女同 | 5 事件 | 6 卜卦',],
                'year' => ['name' => 'year', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生年', 'range' => '1900~2099',],
                'month' => ['name' => 'month', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生月', 'range' => '1~12',],
                'day' => ['name' => 'day', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生日', 'range' => '1~31',],
                'hour' => ['name' => 'hour', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生时', 'range' => '0~23',],
                'minute' => ['name' => 'minute', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '出生分', 'range' => '0~59',],
                'timezone' => ['name' => 'timezone', 'type' => 'int', 'require' => 'true', 'default' => '8（中国时区）', 'desc' => '时区', 'range' => '-12~12',],
                'birth_country' => ['name' => 'birth_country', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '出生省', 'range' => '',],
                'birth_province' => ['name' => 'birth_province', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '出生市', 'range' => '',],
                'birth_city' => ['name' => 'birth_city', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '出生区', 'range' => '',],
                'live_country' => ['name' => 'live_country', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '现居省', 'range' => '',],
                'live_province' => ['name' => 'live_province', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '现居市', 'range' => '',],
                'live_city' => ['name' => 'live_city', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '现居区', 'range' => '',],
                'comments' => ['name' => 'comments', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '标签', 'range' => '自己 | 恋人 | 朋友 | 亲友 | 工作 | 客户 | 案例 | 其他',],
                'isself' => ['name' => 'isself', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '是否自己', 'range' => '档案是否为自己 0 否 | 1 是（自己的档案无法删除，无法更改为其他标签）',],
                'long_deg' => ['name' => 'long_deg', 'type' => 'int', 'require' => 'true', 'default' => '0', 'desc' => '经度-度', 'range' => '0~180',],
                'long_min' => ['name' => 'long_min', 'type' => 'int', 'require' => 'true', 'default' => '0', 'desc' => '经度-分', 'range' => '0~59',],
                'ew' => ['name' => 'ew', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '东经|西经', 'range' => '1|-1',],
                'lat_deg' => ['name' => 'lat_deg', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '纬度-度', 'range' => '0~90',],
                'lat_min' => ['name' => 'lat_min', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '纬度-分', 'range' => '0~59',],
                'ns' => ['name' => 'ns', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '南纬北纬', 'range' => '1|-1',],
                'is_summer' => ['name' => 'is_summer', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '是否开启夏令时', 'range' => '0|1',],
                'avatar' => ['name' => 'avatar', 'type' => 'string', 'require' => 'false', 'default' => '无', 'desc' => '头像地址', 'range' => '',],
            ],
            'delete' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '档案id', 'range' => '',],
            ],
        ];
        return $rules;
    }
}
